﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NB.MGJ.Service;
using NB.MGJ.Service.FWSearch;
using NB.MGJ.Model;
using Common;
using NB.MGJ.Common.MVC;
using NB.MGJ.Model.AntiFake;
using System.Xml;
using NB.MGJ.Service.AntiFake;
using Newtonsoft.Json;
using System.Web.Script.Serialization;
using System.Data;

namespace NB.MGJ.FWSearch.Controllers
{
    public class HomeController : Controller
    {
        public QueryStatisticsService _qsService = new QueryStatisticsService();
        public FWSearchService fw = new FWSearchService();
        /// <summary>
        ///用登录用户IP 
        /// </summary>
        protected string UserIp
        {
            get
            {

                string userIP = string.Empty;

                try
                {
                    if (System.Web.HttpContext.Current == null
                     || System.Web.HttpContext.Current.Request == null
                     || System.Web.HttpContext.Current.Request.ServerVariables == null)
                    {
                        return "";
                    }

                    string CustomerIP = "";

                    CustomerIP = System.Web.HttpContext.Current.Request.Headers["Cdn-Src-Ip"];
                    if (!string.IsNullOrEmpty(CustomerIP))
                    {
                        return CustomerIP;
                    }

                    CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

                    if (!String.IsNullOrEmpty(CustomerIP))
                    {
                        return CustomerIP;
                    }

                    if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
                    {
                        CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

                        if (CustomerIP == null)
                        {
                            CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                        }
                    }
                    else
                    {
                        CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                    }

                    if (string.Compare(CustomerIP, "unknown", true) == 0 || String.IsNullOrEmpty(CustomerIP))
                    {
                        return System.Web.HttpContext.Current.Request.UserHostAddress;
                    }
                    return CustomerIP;
                }
                catch { }

                return userIP;
            }
        }


        public ActionResult Index()
        {
            return View();

        }
        public AntiFakeVerifyService _AntiFakeVerifyService = new AntiFakeVerifyService();
        /// <summary>
        /// 码查询和添加
        /// </summary>
        /// <param name="Code"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public string GetFWSearchList(string Code, string type = "Fw_CodeSecret")
        {
           
            var Codes = "";
            string sqlWhere = "";
            var reply = "";
            var Scodes = MiMa.Jiemi(Code, AppConst.DigitCodeKey);
            var stats = _AntiFakeVerifyService.states(Code);
            if (stats == 2)
            {
                return JsonConvert.SerializeObject(new
                {
                    results = "2"

                });
            }
            var getsearchecode = Scodes.Substring(0, AppConst.SubStrLen);
            var GetEnterId = _AntiFakeVerifyService.GetEnterId(getsearchecode, Code);
            if (getsearchecode == null || GetEnterId == null)
            {
                return JsonConvert.SerializeObject(new
                {
                    results = "-1",
                    res = ""
                });
            }//如果输入错误码
           
            if (GetEnterId.Length == 5 || GetEnterId.Length == 1)
            {
                GetEnterId = "000" + GetEnterId;
            }
            else if (GetEnterId.Length == 6 || GetEnterId.Length == 2)
            {
                GetEnterId = "00" + GetEnterId;
            }
            else if (GetEnterId.Length == 7 || GetEnterId.Length == 3)
            {
                GetEnterId = "0" + GetEnterId;
            }



            int EnterCode = int.Parse(getsearchecode);
            int err = _AntiFakeVerifyService.GetCodes(Code);
            if (err == 0)
            {
                reply = _AntiFakeVerifyService.ReplyInfoService(EnterCode);
            }
            else
            {
                if (!string.IsNullOrEmpty(Code))
                {

                    if (!string.IsNullOrEmpty(Code))
                    {
                        sqlWhere = string.Format(@"  AND {0}='{1}'", type, Code);
                    }

                }

            }
            if (type == "Fw_CodeSecret")
            {
                Codes = MiMa.Jiemi(Code, AppConst.DigitCodeKey);
            }
            string fCode = Codes.Substring(0, AppConst.SubStrLen);
            string eCode = Codes.Substring(0, 4);
            string bcode = fCode.Substring(4, AppConst.SubBatchLen);
            var result = _AntiFakeVerifyService.GetCodeService(eCode, fCode, Codes, bcode, sqlWhere);

            var rs = new CodeLog
            {
                Fw_SCode = result != null ? Scodes : Codes,
                Fw_Code = result != null ? Code : null,
                QueryType = 1,
                QueryTime = DateTime.Now,
                QueryIp = UserIp,


                Valid = result == null || result.Rows.Count == 0 ? 0 : 1,
                ProductId = result != null && !(result.Rows[0]["ProductId"] is DBNull) ? Convert.ToInt32(result.Rows[0]["ProductId"]) : 0,
                EnterpriseId = result != null && !(result.Rows[0]["EnterpriseId"] is DBNull) ? Convert.ToInt32(result.Rows[0]["EnterpriseId"]) : 0
            };

            FWSearchService.UpdateAntifakeLog_Provice_City(rs);

            _AntiFakeVerifyService.AddCodeSearchLog(rs, GetEnterId, Code);
            return JsonConvert.SerializeObject(new
            {
                results = Serialize(result),
                res = reply,
                loginfo = Serialize(_AntiFakeVerifyService.GetwebCodeLog(GetEnterId, Code)),
                num = _AntiFakeVerifyService.searchtimes(Code, GetEnterId),
                firsttime = _AntiFakeVerifyService.FirstSearch(Code, GetEnterId),
                QueryIp = UserIp

            });


        }

        public string Serialize(DataTable dt)
        {
            if (dt == null)
            {
                return "-1";
            }
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
            foreach (DataRow dr in dt.Rows)
            {
                Dictionary<string, object> result = new Dictionary<string, object>();
                foreach (DataColumn dc in dt.Columns)
                {
                    result.Add(dc.ColumnName, dr[dc].ToString());
                }
                list.Add(result);
            }
            return serializer.Serialize(list);
        }


    }


}
